import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:async';

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lcrealtime/Common/Global.dart';
import 'package:lcrealtime/States/GlobalEvent.dart';
import 'package:leancloud_official_plugin/leancloud_plugin.dart';
import 'package:leancloud_storage/leancloud.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:flutter_plugin_record/index.dart';

class UIPage extends StatefulWidget {
  @override
  _PageState createState() => _PageState();
}

String userName = "Tom";

class _PageState extends State<UIPage> {
  var _listController = new ScrollController();
  TextEditingController _messController = new TextEditingController();
  final ImagePicker _imagePicker = ImagePicker();
  Client currentClient = Client(id: userName );
  Set<String> _selectedClientList = new Set();
  Conversation conversation;
  var list;
  @override
  void initState() {
    String jsonStr = '[{"msg":"Tom","me":true}]';
    list = json.decode(jsonStr);
    onMessage();
    super.initState();
  }
  void onMessage  () async{
    await currentClient.open();
    print(" onMessage 是执行了的 ");
    _selectedClientList.add("Tom");
    _selectedClientList.add("Bob");

    // 构建对象

    LCQuery<LCObject> query = new LCQuery('Room');  query.whereEqualTo('to', 'admin');
    LCObject obj = await query.first();
    if(obj==null){
      conversation = await currentClient.createConversation(  isUnique: true,  members: _selectedClientList,  name: 'test');

      LCObject todo = LCObject("Room"); todo["from"] = userName ; todo["to"] = "admin"; todo["room"] = conversation.id;
      await todo.save();
    }else{
      conversation = await currentClient.
      createConversation(  isUnique: true,  members: _selectedClientList,  name: 'test');

    }


    mess.on(MyEvent.NewMessage, (message) {
      if (message != null) {
        if (message is ImageMessage) {
          list.add(json.decode('{"url":"'+ message.url +  '","me":true}'));
        }
        if (message is TextMessage) {
          list.add(json.decode('{"msg":"'+ message.text +  '","me":true}'));
        }

        tobuttom();
      }
    });

    currentClient.onMessage = ({Client client, Conversation conversation, Message message,}) {
      if(message is TextMessage){
        list.add(json.decode('{"msg":"'+ message.text +  '","me":false}'));
        tobuttom();
      }
    };
  }

  tobuttom({ type ='timer' }) async{
    setState(() {});
    if(type =='curve'){
      _listController.animateTo( _listController.position.maxScrollExtent, duration: new Duration(milliseconds: 300), curve: Curves.bounceIn,);
    }else{
      Timer(Duration(seconds:1), () {_listController.jumpTo(_listController.position.maxScrollExtent);});
    }
  }

  test() async{
    currentClient = Client(id: "Bob");
    conversation = await currentClient.createConversation(  isUnique: true,  members: _selectedClientList,  name: 'test');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("聊天页面"), centerTitle: true,),
        body: new Column(
            children: <Widget>[
              Flexible(  child:
                 Container(
                    margin:  EdgeInsets.fromLTRB(15, 10, 15, 0),
                    width:  MediaQuery.of(context).size.width * 1,
                    child: ListView.builder(
                      controller: _listController,
                      itemCount: list.length,
                      itemBuilder: (context, index) { return renderline(index,list[index]);},
                    ),
                  )
              ),
              Divider(height: 1.0),
              Row(  children: [
                    InkWell(onTap: (){
                      _onImageButtonPressed(ImageSource.camera, context: context);
                    }, child:  Icon(Icons.add, size: 50.0, color: Colors.blue),),
                    SizedBox(width:  MediaQuery.of(context).size.width * 0.6, child:  TextField(controller: _messController,),),
                    RaisedButton(child: Text("发送"), onPressed: () {sendTextMessage();},)
                  ])
            ]));
  }


  void _onImageButtonPressed(ImageSource source, {BuildContext context}) async {
    final _imageFile = await _imagePicker.getImage(
      source: source,
      maxWidth: MediaQuery.of(context).size.width * 0.4,
      maxHeight: MediaQuery.of(context).size.width * 0.6,
      imageQuality: 70,
    );
    Image image = Image.file(File(_imageFile.path));
    double imageHeight = 250;
    image.image.resolve(new ImageConfiguration()).addListener(new ImageStreamListener((ImageInfo info, bool _) {
      imageHeight = info.image.height.toDouble();
    }));
    Uint8List bytes = await _imageFile.readAsBytes();
    LCFile file = LCFile.fromBytes('imageMessage.png', bytes);

    await file.save(onProgress: (int count, int total) {
      print('$count/$total');
      if (count == total) {
        sendImageMessage(file.data, imageHeight);
      }
    });
  }

  void sendImageMessage(Uint8List binaryData, double imageHeight) async {
    try {
      ImageMessage imageMessage = ImageMessage.from(binaryData: binaryData);
      await conversation.send(message: imageMessage);
      mess.emit(MyEvent.ImageMessageHeight, imageHeight);
      mess.emit(MyEvent.NewMessage, imageMessage);
      setState(() {
        _messController.clear();
      });
    } catch (e) {
      showToastRed(e.toString());
      print(e.toString());
    }
  }




  Widget getSizedBox(msg){
    if(msg['url']!=null){
      return SizedBox(width: MediaQuery.of(context).size.width * 0.6, child:   Image.network(msg['url']),);
    }else{
      return SizedBox( child: Text( msg['msg']),);
    }
  }
  Widget  renderline(index,msg){
    if(msg['me']){
      return Row(children: <Widget>[ Icon(Icons.access_alarm, size: 50.0, color: Colors.blue),  getSizedBox(msg),],);
    }else{
      return Row(
          mainAxisAlignment:MainAxisAlignment.end,
          children: <Widget>[ getSizedBox(msg),  Icon(Icons.sms, size: 50.0, color: Colors.blue),], );
    }
  }
  /*********************************/
  void sendTextMessage() async {
    if (_messController.text != null && _messController.text != '') {
      try {
        TextMessage textMessage = TextMessage();
        textMessage.text = _messController.text;
        await conversation.send(message: textMessage);
        mess.emit(MyEvent.NewMessage, textMessage);
        _messController.text = "";
      } catch (e) {
        showToastRed(e.toString());
        print(e.toString());
      }
    } else {
      showToastRed('未输入消息');
    }
  }
}